{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DjUA6S30k52h"
      },
      "source": [
        "##### Copyright 2021 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "SpNWyqewk8fE"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6x1ypzczQCwy"
      },
      "source": [
        "# Model analysis using TFX Pipeline and TensorFlow Model Analysis\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HU9YYythm0dx"
      },
      "source": [
        "Note: We recommend running this tutorial in a Colab notebook, with no setup required!  Just click \"Run in Google Colab\".\n",
        "\n",
        "<div class=\"devsite-table-wrapper\"><table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "<td><a target=\"_blank\" href=\"https://www.tensorflow.org/tfx/tutorials/tfx/penguin_tfma\">\n",
        "<img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\"/>View on TensorFlow.org</a></td>\n",
        "<td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tfx/blob/master/docs/tutorials/tfx/penguin_tfma.ipynb\">\n",
        "<img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\">Run in Google Colab</a></td>\n",
        "<td><a target=\"_blank\" href=\"https://github.com/tensorflow/tfx/tree/master/docs/tutorials/tfx/penguin_tfma.ipynb\">\n",
        "<img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\">View source on GitHub</a></td>\n",
        "<td><a href=\"https://storage.googleapis.com/tensorflow_docs/tfx/docs/tutorials/tfx/penguin_tfma.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a></td>\n",
        "</table></div>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_VuwrlnvQJ5k"
      },
      "source": [
        "In this notebook-based tutorial, we will create and run a TFX pipeline\n",
        "which creates a simple classification model and analyzes its performance\n",
        "across multiple runs. This notebook is based on the TFX pipeline we built in\n",
        "[Simple TFX Pipeline Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple).\n",
        "If you have not read that tutorial yet, you should read it before proceeding\n",
        "with this notebook.\n",
        "\n",
        "As you tweak your model or train it with a new dataset, you need to check\n",
        "whether your model has improved or become worse. Just checking top-level\n",
        "metrics like accuracy might not be enough. Every trained model should be\n",
        "evaluated before it is pushed to production.\n",
        "\n",
        "We will add an `Evaluator` component to the pipeline created in the previous\n",
        "tutorial. The Evaluator component performs deep analysis for your models and\n",
        "compare the new model against a baseline to determine they are \"good enough\".\n",
        "It is implemented using the\n",
        "[TensorFlow Model Analysis](https://www.tensorflow.org/tfx/guide/tfma) library.\n",
        "\n",
        "Please see\n",
        "[Understanding TFX Pipelines](https://www.tensorflow.org/tfx/guide/understanding_tfx_pipelines)\n",
        "to learn more about various concepts in TFX."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Fmgi8ZvQkScg"
      },
      "source": [
        "## Set Up\n",
        "The Set up process is the same as the previous tutorial.\n",
        "\n",
        "We first need to install the TFX Python package and download\n",
        "the dataset which we will use for our model.\n",
        "\n",
        "### Upgrade Pip\n",
        "\n",
        "To avoid upgrading Pip in a system when running locally,\n",
        "check to make sure that we are running in Colab.\n",
        "Local systems can of course be upgraded separately."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "as4OTe2ukSqm"
      },
      "outputs": [],
      "source": [
        "try:\n",
        "  import colab\n",
        "  !pip install --upgrade pip\n",
        "except:\n",
        "  pass"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MZOYTt1RW4TK"
      },
      "source": [
        "### Install TFX\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iyQtljP-qPHY"
      },
      "outputs": [],
      "source": [
        "!pip install -U tfx"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EwT0nov5QO1M"
      },
      "source": [
        "### Did you restart the runtime?\n",
        "\n",
        "If you are using Google Colab, the first time that you run\n",
        "the cell above, you must restart the runtime by clicking\n",
        "above \"RESTART RUNTIME\" button or using \"Runtime > Restart\n",
        "runtime ...\" menu. This is because of the way that Colab\n",
        "loads packages."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BDnPgN8UJtzN"
      },
      "source": [
        "Check the TensorFlow and TFX versions."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6jh7vKSRqPHb"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "print('TensorFlow version: {}'.format(tf.__version__))\n",
        "from tfx import v1 as tfx\n",
        "print('TFX version: {}'.format(tfx.__version__))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aDtLdSkvqPHe"
      },
      "source": [
        "### Set up variables\n",
        "\n",
        "There are some variables used to define a pipeline. You can customize these\n",
        "variables as you want. By default all output from the pipeline will be\n",
        "generated under the current directory."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EcUseqJaE2XN"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "PIPELINE_NAME = \"penguin-tfma\"\n",
        "\n",
        "# Output directory to store artifacts generated from the pipeline.\n",
        "PIPELINE_ROOT = os.path.join('pipelines', PIPELINE_NAME)\n",
        "# Path to a SQLite DB file to use as an MLMD storage.\n",
        "METADATA_PATH = os.path.join('metadata', PIPELINE_NAME, 'metadata.db')\n",
        "# Output directory where created models from the pipeline will be exported.\n",
        "SERVING_MODEL_DIR = os.path.join('serving_model', PIPELINE_NAME)\n",
        "\n",
        "from absl import logging\n",
        "logging.set_verbosity(logging.INFO)  # Set default logging level."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8F2SRwRLSYGa"
      },
      "source": [
        "### Prepare example data\n",
        "We will use the same\n",
        "[Palmer Penguins dataset](https://allisonhorst.github.io/palmerpenguins/articles/intro.html).\n",
        "\n",
        "There are four numeric features in this dataset which were already normalized\n",
        "to have range [0,1]. We will build a classification model which predicts the\n",
        "`species` of penguins."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "11J7XiCq6AFP"
      },
      "source": [
        "Because TFX ExampleGen reads inputs from a directory, we need to create a\n",
        "directory and copy dataset to it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4fxMs6u86acP"
      },
      "outputs": [],
      "source": [
        "import urllib.request\n",
        "import tempfile\n",
        "\n",
        "DATA_ROOT = tempfile.mkdtemp(prefix='tfx-data')  # Create a temporary directory.\n",
        "_data_url = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/penguin/data/labelled/penguins_processed.csv'\n",
        "_data_filepath = os.path.join(DATA_ROOT, \"data.csv\")\n",
        "urllib.request.urlretrieve(_data_url, _data_filepath)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nH6gizcpSwWV"
      },
      "source": [
        "## Create a pipeline\n",
        "\n",
        "We will add an [`Evaluator`](https://www.tensorflow.org/tfx/guide/evaluator)\n",
        "component to the pipeline we created in the\n",
        "[Simple TFX Pipeline Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple).\n",
        "\n",
        "An Evaluator component requires input data from an `ExampleGen` component and\n",
        "a model from a `Trainer` component and a\n",
        "[`tfma.EvalConfig`](https://www.tensorflow.org/tfx/model_analysis/api_docs/python/tfma/EvalConfig)\n",
        "object. We can optionally supply a baseline model which can be used to compare\n",
        "metrics with the newly trained model.\n",
        "\n",
        "An evaluator creates two kinds of output artifacts, `ModelEvaluation` and\n",
        "`ModelBlessing`. ModelEvaluation contains the detailed evaluation result which\n",
        "can be investigated and visualized further with TFMA library. ModelBlessing\n",
        "contains a boolean result whether the model passed given criteria and can be\n",
        "used in later components like a Pusher as a signal.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lOjDv93eS5xV"
      },
      "source": [
        "### Write model training code\n",
        "\n",
        "We will use the same model code as in the\n",
        "[Simple TFX Pipeline Tutorial](https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aES7Hv5QTDK3"
      },
      "outputs": [],
      "source": [
        "_trainer_module_file = 'penguin_trainer.py'"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Gnc67uQNTDfW"
      },
      "outputs": [],
      "source": [
        "%%writefile {_trainer_module_file}\n",
        "\n",
        "# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple\n",
        "\n",
        "from typing import List\n",
        "from absl import logging\n",
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "from tensorflow_transform.tf_metadata import schema_utils\n",
        "\n",
        "from tfx.components.trainer.executor import TrainerFnArgs\n",
        "from tfx.components.trainer.fn_args_utils import DataAccessor\n",
        "from tfx_bsl.tfxio import dataset_options\n",
        "from tensorflow_metadata.proto.v0 import schema_pb2\n",
        "\n",
        "_FEATURE_KEYS = [\n",
        "    'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g'\n",
        "]\n",
        "_LABEL_KEY = 'species'\n",
        "\n",
        "_TRAIN_BATCH_SIZE = 20\n",
        "_EVAL_BATCH_SIZE = 10\n",
        "\n",
        "# Since we're not generating or creating a schema, we will instead create\n",
        "# a feature spec.  Since there are a fairly small number of features this is\n",
        "# manageable for this dataset.\n",
        "_FEATURE_SPEC = {\n",
        "    **{\n",
        "        feature: tf.io.FixedLenFeature(shape=[1], dtype=tf.float32)\n",
        "           for feature in _FEATURE_KEYS\n",
        "       },\n",
        "    _LABEL_KEY: tf.io.FixedLenFeature(shape=[1], dtype=tf.int64)\n",
        "}\n",
        "\n",
        "\n",
        "def _input_fn(file_pattern: List[str],\n",
        "              data_accessor: DataAccessor,\n",
        "              schema: schema_pb2.Schema,\n",
        "              batch_size: int = 200) -> tf.data.Dataset:\n",
        "  \"\"\"Generates features and label for training.\n",
        "\n",
        "  Args:\n",
        "    file_pattern: List of paths or patterns of input tfrecord files.\n",
        "    data_accessor: DataAccessor for converting input to RecordBatch.\n",
        "    schema: schema of the input data.\n",
        "    batch_size: representing the number of consecutive elements of returned\n",
        "      dataset to combine in a single batch\n",
        "\n",
        "  Returns:\n",
        "    A dataset that contains (features, indices) tuple where features is a\n",
        "      dictionary of Tensors, and indices is a single Tensor of label indices.\n",
        "  \"\"\"\n",
        "  return data_accessor.tf_dataset_factory(\n",
        "      file_pattern,\n",
        "      dataset_options.TensorFlowDatasetOptions(\n",
        "          batch_size=batch_size, label_key=_LABEL_KEY),\n",
        "      schema=schema).repeat()\n",
        "\n",
        "\n",
        "def _build_keras_model() -> tf.keras.Model:\n",
        "  \"\"\"Creates a DNN Keras model for classifying penguin data.\n",
        "\n",
        "  Returns:\n",
        "    A Keras Model.\n",
        "  \"\"\"\n",
        "  # The model below is built with Functional API, please refer to\n",
        "  # https://www.tensorflow.org/guide/keras/overview for all API options.\n",
        "  inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS]\n",
        "  d = keras.layers.concatenate(inputs)\n",
        "  for _ in range(2):\n",
        "    d = keras.layers.Dense(8, activation='relu')(d)\n",
        "  outputs = keras.layers.Dense(3)(d)\n",
        "\n",
        "  model = keras.Model(inputs=inputs, outputs=outputs)\n",
        "  model.compile(\n",
        "      optimizer=keras.optimizers.Adam(1e-2),\n",
        "      loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "      metrics=[keras.metrics.SparseCategoricalAccuracy()])\n",
        "\n",
        "  model.summary(print_fn=logging.info)\n",
        "  return model\n",
        "\n",
        "\n",
        "# TFX Trainer will call this function.\n",
        "def run_fn(fn_args: TrainerFnArgs):\n",
        "  \"\"\"Train the model based on given args.\n",
        "\n",
        "  Args:\n",
        "    fn_args: Holds args used to train the model as name/value pairs.\n",
        "  \"\"\"\n",
        "\n",
        "  # This schema is usually either an output of SchemaGen or a manually-curated\n",
        "  # version provided by pipeline author. A schema can also derived from TFT\n",
        "  # graph if a Transform component is used. In the case when either is missing,\n",
        "  # `schema_from_feature_spec` could be used to generate schema from very simple\n",
        "  # feature_spec, but the schema returned would be very primitive.\n",
        "  schema = schema_utils.schema_from_feature_spec(_FEATURE_SPEC)\n",
        "\n",
        "  train_dataset = _input_fn(\n",
        "      fn_args.train_files,\n",
        "      fn_args.data_accessor,\n",
        "      schema,\n",
        "      batch_size=_TRAIN_BATCH_SIZE)\n",
        "  eval_dataset = _input_fn(\n",
        "      fn_args.eval_files,\n",
        "      fn_args.data_accessor,\n",
        "      schema,\n",
        "      batch_size=_EVAL_BATCH_SIZE)\n",
        "\n",
        "  model = _build_keras_model()\n",
        "  model.fit(\n",
        "      train_dataset,\n",
        "      steps_per_epoch=fn_args.train_steps,\n",
        "      validation_data=eval_dataset,\n",
        "      validation_steps=fn_args.eval_steps)\n",
        "\n",
        "  # The result of the training should be saved in `fn_args.serving_model_dir`\n",
        "  # directory.\n",
        "  model.save(fn_args.serving_model_dir, save_format='tf')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w3OkNz3gTLwM"
      },
      "source": [
        "### Write a pipeline definition\n",
        "\n",
        "We will define a function to create a TFX pipeline. In addition to the\n",
        "Evaluator component we mentioned above, we will add one more node called\n",
        "[`Resolver`](https://www.tensorflow.org/tfx/api_docs/python/tfx/dsl/components/common/resolver/Resolver).\n",
        "To check a new model is getting better than previous model, we need to compare\n",
        "it against a previous published model, called baseline.\n",
        "[ML Metadata(MLMD)](https://www.tensorflow.org/tfx/guide/mlmd) tracks all\n",
        "previous artifacts of the pipeline and `Resolver` can find what was the latest\n",
        "*blessed* model -- a model passed Evaluator successfully -- from MLMD using a\n",
        "strategy class called `LatestBlessedModelStrategy`.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "M49yYVNBTPd4"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_analysis as tfma\n",
        "\n",
        "def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,\n",
        "                     module_file: str, serving_model_dir: str,\n",
        "                     metadata_path: str) -> tfx.dsl.Pipeline:\n",
        "  \"\"\"Creates a three component penguin pipeline with TFX.\"\"\"\n",
        "  # Brings data into the pipeline.\n",
        "  example_gen = tfx.components.CsvExampleGen(input_base=data_root)\n",
        "\n",
        "  # Uses user-provided Python function that trains a model.\n",
        "  trainer = tfx.components.Trainer(\n",
        "      module_file=module_file,\n",
        "      examples=example_gen.outputs['examples'],\n",
        "      train_args=tfx.proto.TrainArgs(num_steps=100),\n",
        "      eval_args=tfx.proto.EvalArgs(num_steps=5))\n",
        "\n",
        "  # NEW: Get the latest blessed model for Evaluator.\n",
        "  model_resolver = tfx.dsl.Resolver(\n",
        "      strategy_class=tfx.dsl.experimental.LatestBlessedModelStrategy,\n",
        "      model=tfx.dsl.Channel(type=tfx.types.standard_artifacts.Model),\n",
        "      model_blessing=tfx.dsl.Channel(\n",
        "          type=tfx.types.standard_artifacts.ModelBlessing)).with_id(\n",
        "              'latest_blessed_model_resolver')\n",
        "\n",
        "  # NEW: Uses TFMA to compute evaluation statistics over features of a model and\n",
        "  #   perform quality validation of a candidate model (compared to a baseline).\n",
        "\n",
        "  eval_config = tfma.EvalConfig(\n",
        "      model_specs=[tfma.ModelSpec(label_key='species')],\n",
        "      slicing_specs=[\n",
        "          # An empty slice spec means the overall slice, i.e. the whole dataset.\n",
        "          tfma.SlicingSpec(),\n",
        "          # Calculate metrics for each penguin species.\n",
        "          tfma.SlicingSpec(feature_keys=['species']),\n",
        "          ],\n",
        "      metrics_specs=[\n",
        "          tfma.MetricsSpec(per_slice_thresholds={\n",
        "              'sparse_categorical_accuracy':\n",
        "                  tfma.config.PerSliceMetricThresholds(thresholds=[\n",
        "                      tfma.PerSliceMetricThreshold(\n",
        "                          slicing_specs=[tfma.SlicingSpec()],\n",
        "                          threshold=tfma.MetricThreshold(\n",
        "                              value_threshold=tfma.GenericValueThreshold(\n",
        "                                   lower_bound={'value': 0.6}),\n",
        "                              # Change threshold will be ignored if there is no\n",
        "                              # baseline model resolved from MLMD (first run).\n",
        "                              change_threshold=tfma.GenericChangeThreshold(\n",
        "                                  direction=tfma.MetricDirection.HIGHER_IS_BETTER,\n",
        "                                  absolute={'value': -1e-10}))\n",
        "                       )]),\n",
        "          })],\n",
        "      )\n",
        "  evaluator = tfx.components.Evaluator(\n",
        "      examples=example_gen.outputs['examples'],\n",
        "      model=trainer.outputs['model'],\n",
        "      baseline_model=model_resolver.outputs['model'],\n",
        "      eval_config=eval_config)\n",
        "\n",
        "  # Checks whether the model passed the validation steps and pushes the model\n",
        "  # to a file destination if check passed.\n",
        "  pusher = tfx.components.Pusher(\n",
        "      model=trainer.outputs['model'],\n",
        "      model_blessing=evaluator.outputs['blessing'], # Pass an evaluation result.\n",
        "      push_destination=tfx.proto.PushDestination(\n",
        "          filesystem=tfx.proto.PushDestination.Filesystem(\n",
        "              base_directory=serving_model_dir)))\n",
        "\n",
        "  components = [\n",
        "      example_gen,\n",
        "      trainer,\n",
        "\n",
        "      # Following two components were added to the pipeline.\n",
        "      model_resolver,\n",
        "      evaluator,\n",
        "\n",
        "      pusher,\n",
        "  ]\n",
        "\n",
        "  return tfx.dsl.Pipeline(\n",
        "      pipeline_name=pipeline_name,\n",
        "      pipeline_root=pipeline_root,\n",
        "      metadata_connection_config=tfx.orchestration.metadata\n",
        "      .sqlite_metadata_connection_config(metadata_path),\n",
        "      components=components)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mIcu1LeeQbMt"
      },
      "source": [
        "We need to supply the following information to the Evaluator via `eval_config`:\n",
        "- Additional metrics to configure (if want more metrics than defined in model).\n",
        "- Slices to configure\n",
        "- Model validations thresholds to verify if validation to be included\n",
        "\n",
        "Because `SparseCategoricalAccuracy` was already included in the\n",
        "`model.compile()` call, it will be included in the analysis automatically. So\n",
        "we do not add any additional metrics here. `SparseCategoricalAccuracy` will be\n",
        "used to decide whether the model is good enough, too.\n",
        "\n",
        "We compute the metrics for the whole dataset and for each penguin species.\n",
        "`SlicingSpec` specifies how we aggregate the declared metrics.\n",
        "\n",
        "There are two thresholds that a new model should pass, one is an absolute\n",
        "threshold of 0.6 and the other is a relative threshold that it should\n",
        "be higher than the baseline model. When you run the pipeline for the first\n",
        "time, the `change_threshold` will be ignored and only the value_threshold will\n",
        "be checked. If you run the pipeline more than once, the `Resolver` will find a\n",
        "model from the previous run and it will be used as a baseline model for the\n",
        "comparison.\n",
        "\n",
        "See [Evaluator component guide](https://www.tensorflow.org/tfx/guide/evaluator#using_the_evaluator_component) for more information."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mJbq07THU2GV"
      },
      "source": [
        "## Run the pipeline\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7mp0AkmrPdUb"
      },
      "source": [
        "We will use `LocalDagRunner` as in the previous tutorial."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fAtfOZTYWJu-"
      },
      "outputs": [],
      "source": [
        "tfx.orchestration.LocalDagRunner().run(\n",
        "  _create_pipeline(\n",
        "      pipeline_name=PIPELINE_NAME,\n",
        "      pipeline_root=PIPELINE_ROOT,\n",
        "      data_root=DATA_ROOT,\n",
        "      module_file=_trainer_module_file,\n",
        "      serving_model_dir=SERVING_MODEL_DIR,\n",
        "      metadata_path=METADATA_PATH))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ppERq0Mj6xvW"
      },
      "source": [
        "When the pipeline completed, you should be able to see something like following:\n",
        "```\n",
        "INFO:absl:Blessing result True written to pipelines/penguin-tfma/Evaluator/blessing/4.\n",
        "```\n",
        "Or you can also check manually the output directory where the generated\n",
        "artifacts are stored. If you visit\n",
        "`pipelines/penguin-tfma/Evaluator/blessing/` with a file broswer, you can see a\n",
        "file with a name `BLESSED` or `NOT_BLESSED` according to the evaluation result.\n",
        "\n",
        "If the blessing result is `False`, Pusher will refuse to push the model to the\n",
        "`serving_model_dir`, because the model is not good enough to be used in\n",
        "production."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zR9HcqMSTizW"
      },
      "source": [
        "You can run the pipeline again possibly with different evaluation configs. Even\n",
        "if you run the pipeline with the exact same config and dataset, the trained\n",
        "model might be slightly different due to the inherent randomness of the model\n",
        "training which can lead to a `NOT_BLESSED` model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cWcBI-bjoVTO"
      },
      "source": [
        "### Examine outputs of the pipeline\n",
        "\n",
        "You can use TFMA to investigate and visualize the evaluation result in\n",
        "ModelEvaluation artifact."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IXZ0N5GHm_tX"
      },
      "source": [
        "> **NOTE: If you are not on Colab, Install Jupyter Extensions.**\n",
        "You need an TensorFlow Model Analysis extension to see the visualization from\n",
        "TFMA. This extension is already installed on Google Colab, but you might need\n",
        "to install it if you are running this notebook on other environments.\n",
        "See installation direction of Jupyter extension in the\n",
        "[Install guide](https://github.com/tensorflow/model-analysis#installation).\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9VIWOBq0opag"
      },
      "source": [
        "#### Get analysis result from output artifacts\n",
        "\n",
        "You can use MLMD APIs to locate these outputs programatically. First, we will\n",
        "define some utility functions to search for the output artifacts that were just\n",
        "produced."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aiK6zbeAg3X5"
      },
      "outputs": [],
      "source": [
        "from ml_metadata.proto import metadata_store_pb2\n",
        "# Non-public APIs, just for showcase.\n",
        "from tfx.orchestration.portable.mlmd import execution_lib\n",
        "\n",
        "# TODO(b/171447278): Move these functions into the TFX library.\n",
        "\n",
        "def get_latest_artifacts(metadata, pipeline_name, component_id):\n",
        "  \"\"\"Output artifacts of the latest run of the component.\"\"\"\n",
        "  context = metadata.store.get_context_by_type_and_name(\n",
        "      'node', f'{pipeline_name}.{component_id}')\n",
        "  executions = metadata.store.get_executions_by_context(context.id)\n",
        "  latest_execution = max(executions,\n",
        "                         key=lambda e:e.last_update_time_since_epoch)\n",
        "  return execution_lib.get_artifacts_dict(metadata, latest_execution.id, \n",
        "                                          metadata_store_pb2.Event.OUTPUT)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tujLG8sTGZiv"
      },
      "source": [
        "We can find the latest execution of the `Evaluator` component and get output\n",
        "artifacts of it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4FOo6PV5g5Mm"
      },
      "outputs": [],
      "source": [
        "# Non-public APIs, just for showcase.\n",
        "from tfx.orchestration.metadata import Metadata\n",
        "from tfx.types import standard_component_specs\n",
        "\n",
        "metadata_connection_config = tfx.orchestration.metadata.sqlite_metadata_connection_config(\n",
        "    METADATA_PATH)\n",
        "\n",
        "with Metadata(metadata_connection_config) as metadata_handler:\n",
        "  # Find output artifacts from MLMD.\n",
        "  evaluator_output = get_latest_artifacts(metadata_handler, PIPELINE_NAME,\n",
        "                                          'Evaluator')\n",
        "  eval_artifact = evaluator_output[standard_component_specs.EVALUATION_KEY][0]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IXIJR840GpEq"
      },
      "source": [
        "`Evaluator` always returns one evaluation artifact, and we can visualize it\n",
        "using TensorFlow Model Analysis library. For example, following code will\n",
        "render the accuracy metrics for each penguin species."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wTaKoEHrj0Gs"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_analysis as tfma\n",
        "\n",
        "eval_result = tfma.load_eval_result(eval_artifact.uri)\n",
        "tfma.view.render_slicing_metrics(eval_result, slicing_column='species')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nSwaiRQ0JYMZ"
      },
      "source": [
        "If you choose 'sparse_categorical_accuracy' in `Show` drop-down list, you can\n",
        "see the accuracy values per species. You might want to add more slices and\n",
        "check whether your model is good for all distribution and if there is any\n",
        "possible bias."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "08R8qvweThRf"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "Learn more on model analysis at\n",
        "[TensorFlow Model Analysis library tutorial](https://www.tensorflow.org/tfx/tutorials/model_analysis/tfma_basic).\n",
        "\n",
        "You can find more resources on https://www.tensorflow.org/tfx/tutorials.\n",
        "\n",
        "Please see\n",
        "[Understanding TFX Pipelines](https://www.tensorflow.org/tfx/guide/understanding_tfx_pipelines)\n",
        "to learn more about various concepts in TFX.\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "DjUA6S30k52h",
        "lOjDv93eS5xV"
      ],
      "name": "penguin_tfma.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
